/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.excel.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.db.DbFieldType;
import com.je.common.base.constants.excel.ExcelErrorCode;
import com.je.common.base.datasource.runner.SqlRunner;
import com.je.common.base.db.DbFieldVo;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.service.rpc.DocumentInternalRpcService;
import com.je.common.base.service.rpc.SystemVariableRpcService;
import com.je.common.base.spring.SpringContextHolder;
import com.je.common.base.util.ArrayUtils;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.ReflectionUtils;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.model.ExcelParamVo;
import com.je.meta.model.ExcelReturnVo;
import com.je.meta.rpc.excel.ExcelRpcExportService;
import com.je.meta.rpc.excel.ExcelRpcService;
import com.je.meta.service.AbstractExcelServiceImpl;
import com.je.meta.service.ExcelService;
import com.je.meta.service.excel.ExcelExportFactory;
import com.je.meta.service.excel.converter.ExcelExportConverterFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @program: jecloud-meta
 * @author: LIULJ
 * @create: 2021-08-03 13:23
 * @description:
 */
@Service
public class ExcelServiceImpl extends AbstractExcelServiceImpl implements ExcelService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private SystemVariableRpcService systemVariableRpcService;
    @Autowired
    private DocumentInternalRpcService documentInternalRpcService;
    //    @Autowired
//    private PCDataService pcDataService;
    @Autowired
    private ExcelRpcService excelRpcService;

    private static final String COLUMNS = "RESOURCECOLUMN_MORECOLUMNNAME,RESOURCECOLUMN_WIDTH,RESOURCECOLUMN_CODE," +
            "RESOURCECOLUMN_XTYPE,RESOURCECOLUMN_NAME,RESOURCEFIELD_XTYPE,RESOURCEFIELD_CONFIGINFO";

    @Override
    public JSONObject impData(DynaBean groupTemBean, String fileKey, HttpServletRequest request) throws IOException {
        if (StringUtil.isEmpty(groupTemBean.getStr("JE_EXCEL_GROUPTEM_ID"))) {
            //构建创新基础信息
            commonService.buildModelCreateInfo(groupTemBean);
            groupTemBean = commonService.doSave(groupTemBean);
        }
        return impData(groupTemBean.getStr("GROUPCODE"), fileKey, groupTemBean.getStr("JE_EXCEL_GROUPTEM_ID"), request);
    }

    @Override
    public JSONObject impData(String code, String fileKey, HttpServletRequest request) {
        return null;
    }

    @Override
    public JSONObject impData(String code, String fileKey, String groupTemId, HttpServletRequest request) throws IOException {
        //声明返回值
        JSONObject returnObj = new JSONObject();
        if (StringUtil.isNotEmpty(groupTemId)) {
            returnObj.put("groupTemId", groupTemId);
        }
        DynaBean group = metaService.selectOne("JE_CORE_EXCELGROUP", ConditionsWrapper.builder().eq("GROUPCODE", code));
        //声明变量集合，用于解析whereSql的通配符
        Map<String, Object> ddMap = systemVariableRpcService.formatCurrentUserAndCachedVariables();
        ddMap.putAll(getRequestParams(request));
        List<ExcelReturnVo> returnMsgs = new ArrayList<ExcelReturnVo>();
        //全局执行前逻辑
        returnMsgs.add(executeLogic(group.getStr("BEFORE_TYPE"), group.getStr("BEFORE_SQL"), group.getStr("BEFORE_DBNAME"), group.getStr("BEFORE_PROCEDURE"), group.getStr("JE_CORE_EXCELGROUP_ID"), "BEFORE", group.getStr("BEFORE_BEAN"), group.getStr("BEFORE_METHOD"), ddMap, new ExcelParamVo(request, "ALL_BEFORE")));
        //系统处理方式
        //数据预览
        String dataPreview = group.getStr("EXCELGROUP_PRVIEW");
        if ("1".equals(dataPreview)) {
            String delSql = "";
            if (returnObj.containsKey("groupTemId")) {
                delSql = " AND JE_EXCEL_GROUPTEM_ID!='" + returnObj.getString("groupTemId") + "'";
            }
            metaService.executeSql(" DELETE FROM JE_EXCEL_GROUPTEM WHERE JE_CORE_EXCELGROUP_ID='" + group.getStr("JE_CORE_EXCELGROUP_ID") + "'" + delSql);
        }

        //获取文件流
        File file = documentInternalRpcService.readFile(fileKey);
        byte[] bytes = IoUtil.readBytes(FileUtil.getInputStream(file));

        //声明默认值
        List<DynaBean> sheets = metaService.select("JE_CORE_EXCELSHEET", ConditionsWrapper.builder().eq("JE_CORE_EXCELGROUP_ID", group.getStr("JE_CORE_EXCELGROUP_ID")).orderByAsc("SY_ORDERINDEX"));
        Map<String, List<DynaBean>> results = new HashMap<>();
        List<String> sheetNames = new ArrayList<>();
        JSONArray previewSheetInfo = new JSONArray();
        Map<String, Map<String, DynaBean>> allFieldInfos = new HashMap<>();
        for (int sheetIndex = 0; sheetIndex < sheets.size(); sheetIndex++) {
            DynaBean sheet = sheets.get(sheetIndex);
            int sheetOrder = sheet.getInt("SY_ORDERINDEX", 1) - 1;
            String key = "sheet" + sheetOrder;
            //声明字段信息
            List<DynaBean> fields = metaService.select("JE_CORE_EXCELFIELD", ConditionsWrapper.builder().eq("JE_CORE_EXCELSHEET_ID", sheet.getStr("JE_CORE_EXCELSHEET_ID")).orderByAsc("SY_ORDERINDEX"));

            //读取文件
            ExcelReader reader = new ExcelReader(IoUtil.toStream(bytes), sheetOrder, true);
            String tableCode = sheet.getStr("EXCELSHEET_TABLECODE");
            int startRow = sheet.getInt("STARTROWS", 0);
            int endRow = sheet.getInt("EXCELSHEET_JSX", 0);
            String funcCode = sheet.getStr("EXCELSHEET_FUNCCODE");
            String defaultFuncVal = sheet.getStr("DATA_DEFAULTVALUE");
            String defaultCreateInfo = sheet.getStr("DATA_CREATEINFO");
            String sheetName = reader.getSheet().getSheetName();
            sheetNames.add(sheetName);
            sheet.set("SHEETNAME", sheetName);
            //声明默认值
            DynaBean defaultValues = new DynaBean();
            if ("1".equals(defaultFuncVal)) {
                commonService.buildFuncDefaultValues(funcCode, defaultValues);
            }
            List<List<Object>> lists = null;
            if (endRow > startRow && startRow >= 0) {
                lists = reader.read(startRow, endRow);
            } else {
                lists = reader.read(startRow - 1);
            }
            List<DynaBean> datas = new ArrayList<DynaBean>();
            Map<String, DynaBean> fieldInfos = new HashMap<String, DynaBean>();
            Map<String, DynaBean> fieldCodeInfos = new HashMap<String, DynaBean>();
            //自动带值数据集
            Map<String, List<DynaBean>> dzValues = new HashMap<String, List<DynaBean>>();
            //编号字段
            List<String> codeFields = new ArrayList<String>();
            //带值字段集合
            List<String> dzFields = new ArrayList<String>();
            List<String> kxjsFields = new ArrayList<String>();
            //日期处理类型
            List<String> dateFields = new ArrayList<String>();
            List<String> dateTimeFields = new ArrayList<String>();
            for (DynaBean field : fields) {
                String columnName = field.getStr("EXCELFIELD_COLUMN");
                fieldCodeInfos.put(field.getStr("EXCELFIELD_CODE"), field);
                //处理默认值
                String defaultValue = field.getStr("EXCELFIELD_VALUE");
                if (!Strings.isNullOrEmpty(defaultValue) && StringUtil.isNotEmpty(defaultValue) && defaultValue.startsWith("@") && defaultValue.endsWith("@")) {
                    defaultValue = "{" + defaultValue + "}";
                }
                if (!Strings.isNullOrEmpty(defaultValue)) {
                    defaultValues.set(field.getStr("EXCELFIELD_CODE"), StringUtil.parseKeyWord(defaultValue, ddMap));
                }
                if (StringUtil.isNotEmpty(columnName)) {
                    fieldInfos.put(columnName, field);
                }
                if ("codefield".equals(field.getStr("EXCELFIELD_XTYPE"))) {
                    codeFields.add(field.getStr("EXCELFIELD_CODE"));
                }
                if ("datefield".equals(field.getStr("EXCELFIELD_XTYPE"))) {
                    dateFields.add(field.getStr("EXCELFIELD_CODE"));
                }
                if ("datetimefield".equals(field.getStr("EXCELFIELD_XTYPE"))) {
                    dateTimeFields.add(field.getStr("EXCELFIELD_CODE"));
                }
                if ("1".equals(field.getStr("EXCELFIELD_QCKXJS"))) {
                    kxjsFields.add(field.getStr("EXCELFIELD_CODE"));
                }
                excelRpcService.parseAllDzValues(field, ddMap, dzValues, dzFields, getRequestParams(request));
            }
            allFieldInfos.put(key, fieldCodeInfos);
            for (List<Object> vals : lists) {
                DynaBean dynaBean = new DynaBean();
                if ("1".equals(defaultFuncVal)) {
                    dynaBean.setValues(defaultValues.clone().getValues());
                }
                if ("1".equals(defaultCreateInfo)) {
                    commonService.buildModelCreateInfo(dynaBean);
                }
                if (StringUtil.isNotEmpty(tableCode)) {
                    dynaBean.set(BeanService.KEY_TABLE_CODE, tableCode);
                }
                for (int i = 0; i < vals.size(); i++) {
                    String nowName = getExcelColumnName(i);
                    if (fieldInfos.containsKey(nowName)) {
                        DynaBean field = fieldInfos.get(nowName);
                        String fieldCode = field.getStr("EXCELFIELD_CODE");
                        //去除字段值
                        Object excelValue = vals.get(i);
                        if (!Objects.isNull(excelValue) && !Strings.isNullOrEmpty(excelValue.toString())) {
                            dynaBean.set(fieldCode, excelValue);
                        }
                    }
                }
                for (String dzField : dzFields) {
                    DynaBean fieldInfo = fieldCodeInfos.get(dzField);
                    excelRpcService.doSetBeanDzValue(fieldInfo, dynaBean, dzValues, ddMap);
                }
                for (String dateField : dateFields) {
                    String dateValue = dynaBean.getStr(dateField);
                    if (!Strings.isNullOrEmpty(dateValue)) {
                        try {
                            dynaBean.setStr(dateField, DateUtils.formatDate(DateUtils.getDate(dateValue)));
                        } catch (Exception e) {
                            throw new RuntimeException("日期格式错误");
                        }
                    }
                }

                for (String dateTimeField : dateTimeFields) {
                    String dateValue = dynaBean.getStr(dateTimeField);
                    if (!Strings.isNullOrEmpty(dateValue)) {
                        try {
                            dynaBean.setStr(dateTimeField, DateUtils.formatDateTime(DateUtils.getDate(dateValue)));
                        } catch (Exception e) {
                            throw new RuntimeException("日期格式错误");
                        }
                    }
                }

                for (String kxjsCode : kxjsFields) {
                    String val = dynaBean.getStr(kxjsCode);
                    if (StringUtil.isNotEmpty(val)) {
                        String regx = "^((-?\\d+.?\\d*)[Ee]{1}(-?\\d+))$";
                        Pattern pattern = Pattern.compile(regx);
                        if (pattern.matcher(val).matches()) {
//							 DecimalFormat df = new DecimalFormat("0");
//							 val = df.format(val);
                            BigDecimal b = new BigDecimal(val);
                            val = b.toPlainString();
                        }
                    }
                    dynaBean.set(kxjsCode, val);
                }
                dynaBean.set("__CODE__", "1");
                dynaBean.set("__MSG__", "正确");
                datas.add(dynaBean);
            }
            String beforeClType = sheet.getStr("BEFORE_CLTYPE");
            String beforeType = sheet.getStr("BEFORE_TYPE");
            if ("ONE".equals(beforeClType)) {
                for (DynaBean data : datas) {
                    if ("SQL".equals(beforeClType)) {
                        returnMsgs.add(executeLogic("SQL", sheet.getStr("BEFORE_SQL"), "", "", sheet.getStr("JE_CORE_EXCELSHEET_ID"), "BEFORE", "", "", ddMap, new ExcelParamVo(request, results, data, "SHEET_ONE_BEFORE", sheetOrder, sheetName, startRow, fieldCodeInfos)));
                    } else if ("PROCEDURE".equals(beforeType)) {
                        returnMsgs.add(executeLogic("PROCEDURE", "", sheet.getStr("DATA_DBNAME"), sheet.getStr("DATA_PROCEDURE"), sheet.getStr("JE_CORE_EXCELSHEET_ID"), "BEFORE", "", "", ddMap, new ExcelParamVo(request, results, data, "SHEET_ONE_BEFORE", sheetOrder, sheetName, startRow, fieldCodeInfos)));
                        //执行方法插入
                    } else if ("BEAN".equals(beforeType)) {
                        returnMsgs.add(executeLogic("BEAN", "", "", "", "", "DATA", sheet.getStr("BEFORE_BEANNAME"), sheet.getStr("BEFORE_DBNAME"), ddMap, new ExcelParamVo(request, results, data, "SHEET_ONE_BEFORE", sheetOrder, sheetName, startRow, fieldCodeInfos)));
                    }
                }
            } else {
                returnMsgs.add(executeLogic(sheet.getStr("BEFORE_TYPE"), sheet.getStr("BEFORE_SQL"), sheet.getStr("BEFORE_DBNAME"), sheet.getStr("BEFORE_PROCEDURE"), sheet.getStr("JE_CORE_EXCELSHEET_ID"), "BEFORE", sheet.getStr("BEFORE_BEAN"), sheet.getStr("BEFORE_METHOD"), ddMap, new ExcelParamVo(request, results, datas, sheetOrder, sheetName, "SHEET_BEFORE", fieldCodeInfos)));
            }
            if ("1".equals(dataPreview)) {
                if (StringUtil.isEmpty(groupTemId)) {
                    DynaBean groupTem = new DynaBean("JE_EXCEL_GROUPTEM", true);
                    groupTem.set("GROUPNAME", group.getStr("GROUPNAME"));
                    groupTem.set("GROUPCODE", group.getStr("GROUPCODE"));
                    groupTem.set("JE_CORE_EXCELGROUP_ID", group.getStr("JE_CORE_EXCELGROUP_ID"));
                    commonService.buildModelCreateInfo(groupTem);
                    metaService.insert(groupTem);
                    groupTemId = groupTem.getStr("JE_EXCEL_GROUPTEM_ID");
                }
                DynaBean previewConfig = new DynaBean("JE_EXCEL_CONFIGTEMP", true);
                previewConfig.set("GROUPNAME", group.getStr("GROUPNAME"));
                previewConfig.set("GROUPCODE", group.getStr("GROUPCODE"));
                previewConfig.set("SHEETNAME", sheetName);
                previewConfig.set("JE_EXCEL_GROUPTEM_ID", groupTemId);
                previewConfig.set("JE_CORE_EXCELGROUP_ID", group.getStr("JE_CORE_EXCELGROUP_ID"));
                previewConfig.set("CONFIGTEMP_SHEET", sheetOrder);
                previewConfig.set("JE_CORE_EXCELSHEET_ID", sheet.getStr("JE_CORE_EXCELSHEET_ID"));
                previewConfig.set("CONFIGTEMP_SHEETNAME", sheetName);
                commonService.buildModelCreateInfo(previewConfig);
                //声明字段对应
                List<String> fieldConfigs = new ArrayList<String>();
                for (int i = 0; i < fields.size(); i++) {
                    DynaBean field = fields.get(i);
                    fieldConfigs.add("DATATEMP_FIELD" + (i + 1) + "~" + field.getStr("EXCELFIELD_CODE"));
                }
                previewConfig.set("CONFIGTEMP_FIELDCONFIG", StringUtil.buildSplitString(ArrayUtils.getArray(fieldConfigs), ","));
                System.out.println(JSON.toJSONString(previewConfig.fetchFilterValues()));
                metaService.insert(previewConfig);
                int index = 1;
                for (DynaBean data : datas) {
                    DynaBean temData = new DynaBean("JE_EXCEL_DATATEMP", true);
                    for (String fieldConfig : fieldConfigs) {
                        String fieldCode = fieldConfig.split("~")[0];
                        String fieldTarge = fieldConfig.split("~")[1];
                        temData.set(fieldCode, data.getStr(fieldTarge));
                    }
                    temData.set("CODE", data.getStr("__CODE__"));
                    temData.set("MSG", data.getStr("__MSG__"));
                    temData.set("JE_EXCEL_CONFIGTEMP_ID", previewConfig.getStr("JE_EXCEL_CONFIGTEMP_ID"));
                    temData.set("SY_ORDERINDEX", index);
                    commonService.buildModelCreateInfo(temData);
                    metaService.insert(temData);
                    index++;
                }
                //构建每个Sheet的情况
                previewSheetInfo.add(excelRpcService.buildSheetInfoWithSheet(previewConfig.getStr("JE_EXCEL_CONFIGTEMP_ID"), sheetName, sheetOrder, fields, fieldConfigs));
            } else {
                returnMsgs.add(executeLogic(sheet.getStr("AFTER_TYPE"), sheet.getStr("AFTER_SQL"), sheet.getStr("AFTER_DBNAME"), sheet.getStr("AFTER_PROCEDURE"), sheet.getStr("JE_CORE_EXCELSHEET_ID"), "AFTER", sheet.getStr("AFTER_BEAN"), sheet.getStr("AFTER_METHOD"), ddMap, new ExcelParamVo(request, results, datas, sheetOrder, sheetName, "SHEET_AFTER", fieldCodeInfos)));
            }
            results.put(key, datas);
            if ("0".equals(dataPreview)) {
                List<DynaBean> sheetList = new ArrayList<>();
                sheetList.add(sheet);
                returnMsgs.addAll(doData(group, sheetList, results, ddMap, request, allFieldInfos));
            }
        }
        if ("1".equals(dataPreview)) {
            returnObj.put("PREVIEW", "1");
            returnObj.put("SHEETINFO", previewSheetInfo);
        } else {
            returnObj.put("PREVIEW", "0");
        }
        returnObj.put("returnMsgs", returnMsgs);

        return returnObj;
    }

    @Override
    public void impPreviewData(String code, String temIds, HttpServletRequest request, JSONObject returnObj) {
        DynaBean group = metaService.selectOne("JE_CORE_EXCELGROUP", ConditionsWrapper.builder().eq("GROUPCODE", code));
        //声明变量集合，用于解析whereSql的通配符
        Map<String, Object> ddMap = systemVariableRpcService.formatCurrentUserAndCachedVariables();
        ddMap.putAll(getRequestParams(request));
        List<ExcelReturnVo> returnMsgs = new ArrayList<ExcelReturnVo>();
        //全局执行前逻辑
        returnMsgs.add(executeLogic(group.getStr("BEFORE_TYPE"), group.getStr("BEFORE_SQL"), group.getStr("BEFORE_DBNAME"), group.getStr("BEFORE_PROCEDURE"), group.getStr("JE_CORE_EXCELGROUP_ID"), "BEFORE", group.getStr("BEFORE_BEAN"), group.getStr("BEFORE_METHOD"), ddMap, new ExcelParamVo(request, "ALL_BEFORE")));
        //系统处理方式
        List<DynaBean> temConfigs = metaService.select("JE_EXCEL_CONFIGTEMP", ConditionsWrapper.builder().in("JE_EXCEL_CONFIGTEMP_ID", Splitter.on(",").splitToList(temIds)));
        Map<String, List<DynaBean>> results = new HashMap<String, List<DynaBean>>();
        List<DynaBean> sheets = new ArrayList<DynaBean>();
        Map<String, Map<String, DynaBean>> allFieldInfos = new HashMap<String, Map<String, DynaBean>>();
        for (DynaBean temConfig : temConfigs) {
            String fieldConfigStrs = temConfig.getStr("CONFIGTEMP_FIELDCONFIG");
            List<DynaBean> lists = new ArrayList<DynaBean>();
//			Map<String,String> fieldConfigs=new HashMap<String,String>();
//			for(String fieldConfig:fieldConfigStrs.split(",")){
//				fieldConfigs.put(fieldConfig.split("~")[0], fieldConfig.split("~")[1]);
//			}
            DynaBean sheet = metaService.selectOneByPk("JE_CORE_EXCELSHEET", temConfig.getStr("JE_CORE_EXCELSHEET_ID"));
            List<DynaBean> fields = metaService.select("JE_CORE_EXCELFIELD", ConditionsWrapper.builder().eq("JE_CORE_EXCELSHEET_ID", sheet.getStr("JE_CORE_EXCELSHEET_ID")).orderByAsc("SY_ORDERINDEX"));
            Map<String, DynaBean> fieldInfos = new HashMap<String, DynaBean>();
            Map<String, DynaBean> fieldCodeInfos = new HashMap<String, DynaBean>();
            for (DynaBean field : fields) {
                String columnName = field.getStr("EXCELFIELD_COLUMN");
                //处理默认值
                if (StringUtil.isNotEmpty(columnName)) {
                    fieldInfos.put(columnName, field);
                }
            }
            List<DynaBean> datas = metaService.select("JE_EXCEL_DATATEMP", ConditionsWrapper.builder()
                    .eq("JE_EXCEL_CONFIGTEMP_ID", temConfig.getStr("JE_EXCEL_CONFIGTEMP_ID"))
                    .in("CODE", Lists.newArrayList("-1", "1"))
                    .orderByAsc("SY_ORDERINDEX"));
            for (DynaBean data : datas) {
                DynaBean dynaBean = new DynaBean(sheet.getStr("TABLECODE", ""), true);
                for (String fieldConfig : fieldConfigStrs.split(",")) {
                    String thisField = fieldConfig.split("~")[0];
                    String targerField = fieldConfig.split("~")[1];
                    dynaBean.set(targerField, data.get(thisField));
                }
                lists.add(dynaBean);
            }
            sheet.set("SHEETNAME", temConfig.getStr("CONFIGTEMP_SHEETNAME"));
            int sheetOrder = sheet.getInt("SY_ORDERINDEX", 0) - 1;
            String key = "sheet" + sheetOrder;
            results.put(key, lists);
            sheets.add(sheet);
            allFieldInfos.put(key, fieldCodeInfos);
        }
        returnMsgs.addAll(doData(group, sheets, results, ddMap, request, allFieldInfos));
        metaService.executeSql(" DELETE FROM JE_EXCEL_GROUPTEM WHERE JE_CORE_EXCELGROUP_ID='" + group.getStr("JE_CORE_EXCELGROUP_ID") + "'");
        //处理数据
        returnObj.put("returnMsgs", returnMsgs);
    }

    @Override
    public ExcelReturnVo executeLogic(String type, String sql, String datasourceName, String procedureName, String pkValue, String queryType, String beanName, String beanMethod, Map<String, Object> paramValues, ExcelParamVo paramVo) {
        ExcelReturnVo returnVo = new ExcelReturnVo(1, "成功");
        Map<String, Object> beanMap = new HashMap<>();
        if (paramVo.getDynaBean() != null) {
            beanMap = paramVo.getDynaBean().clone().getValues();
        }
        returnVo.setDoType(paramVo.getDoType());
        returnVo.setRowIndex(paramVo.getNowRow());
        returnVo.setSheetIndex(paramVo.getNowSheet());
        if ("SQL".equals(type)) {
            if (StringUtil.isNotEmpty(sql)) {
                sql = StringUtil.parseKeyWord(sql, paramValues);
                sql = StringUtil.parseKeyWord(sql, beanMap);
                metaService.executeSql(sql);
            }
        } else if ("PROCEDURE".equals(type)) {
            List<DynaBean> params = metaService.select("JE_CORE_PRODUREPARAM", ConditionsWrapper.builder().eq("PKVALUE", pkValue).eq("QUERYTYPE", queryType).orderByAsc("SY_ORDERINDEX"));
            List<DbFieldVo> fieldVos = new ArrayList<DbFieldVo>();
            String codeName = "";
            String msgName = "";
            for (DynaBean param : params) {
                String name = param.getStr("NAME", "");
                String fieldType = param.getStr("FIELDTYPE", "");
                String paramType = "1".equals(param.getStr("PARAMTYPE")) ? "out" : "in";
                DbFieldVo fieldVo = new DbFieldVo(name, paramType, fieldType);
                if (DbFieldType.CODE.equals(fieldType)) {
                    codeName = name;
                } else if (DbFieldType.MSG.equals(fieldType)) {
                    msgName = name;
                }
                if ("in".equals(fieldVo.getParamType()) && !ArrayUtils.contains(new String[]{DbFieldType.CURSOR, DbFieldType.MSG, DbFieldType.CODE, DbFieldType.NOWPAGE, DbFieldType.LIMIT, DbFieldType.TOTALCOUNT}, fieldType)) {
                    String defaultValue = param.getStr("DEFAULTVALUE");
                    String fieldCode = param.getStr("NAME");
                    if (StringUtil.isNotEmpty(defaultValue)) {
                        defaultValue = StringUtil.parseKeyWord(defaultValue, paramValues);
                        defaultValue = StringUtil.parseKeyWord(defaultValue, beanMap);
                        fieldVo.setValue(defaultValue);
                    }
                    if ("DATA".equals(queryType) && paramVo.getDynaBean() != null) {
                        Map<String, DynaBean> fieldInfos = paramVo.getFieldInfos();
                        DynaBean bean = paramVo.getDynaBean();
                        if (fieldInfos.containsKey(fieldCode)) {
                            if (bean.containsKey(fieldCode)) {
                                String val = bean.getStr(fieldCode);
                                if (StringUtil.isNotEmpty(val)) {
                                    fieldVo.setValue(val);
                                }
                            }
                        }
                    }
                }
                fieldVos.add(fieldVo);
            }

            Map<String, Object> map = new HashMap();
            Object[] paramLengths = new Object[fieldVos.size()];
            if (StringUtil.isEmpty(datasourceName) || "local".equals(datasourceName)) {
                //todo 此处微服务改造，先注释，后续放开
//                map = metaService.queryMapProcedure("{call " + procedureName + "(" + pcDataService.getCallParams(paramLengths) + ")}", fieldVos);
            } else {
                SqlRunner sqlRunner = SqlRunner.getInstance(datasourceName);
//                map = sqlRunner.queryMapProcedure("{call " + procedureName + "(" + pcDataService.getCallParams(paramLengths) + ")}", fieldVos);
                map = null;
            }
            if (StringUtil.isNotEmpty(codeName)) {
                int code = Integer.parseInt(StringUtil.getDefaultValue(map.get(codeName), "1"));
                returnVo.setCode(code);
                String msg = "";
                if (StringUtil.isNotEmpty(msgName)) {
                    msg = map.get(msgName) + "";
                    returnVo.setMsg(msg);
                }
                if (paramVo.getDynaBean() != null) {
                    paramVo.getDynaBean().set("__CODE__", code);
                    paramVo.getDynaBean().set("__MSG__", msg);
                }
                if (ExcelErrorCode.STOPERROR == code) {
                    throw new PlatformException(msg, PlatformExceptionEnum.JE_CORE_EXCEL_IMPDATA_ERROR, new Object[]{returnVo});
//					throw new ExcelDataException(msg);
                }
            }
        } else if ("BEAN".equals(type)) {
            if (StringUtil.isNotEmpty(beanName) && StringUtil.isNotEmpty(beanMethod)) {
                //处理前执行类
                Object bean = SpringContextHolder.getBean(beanName);
                returnVo = (ExcelReturnVo) ReflectionUtils.getInstance().invokeMethod(bean, beanMethod, new Object[]{paramVo});
                if (ExcelErrorCode.STOPERROR == returnVo.getCode()) {
                    throw new PlatformException(returnVo.getMsg(), PlatformExceptionEnum.JE_CORE_EXCEL_IMPDATA_ERROR, new Object[]{returnVo});
                }
            }
        }
        return returnVo;
    }

    @Override
    public void implExcelFields(DynaBean dynaBean) {
        String pkValue = dynaBean.getStr("JE_CORE_EXCELSHEET_ID");
        String funcId = dynaBean.getStr("funcId");
        String tableCode = dynaBean.getStr("tableCode");
        metaService.executeSql("DELETE FROM JE_CORE_EXCELFIELD WHERE JE_CORE_EXCELSHEET_ID={0}", pkValue);
        //AND RESOURCECOLUMN_XTYPE!='morecolumn'
        if (StringUtil.isNotEmpty(funcId)) {
            List<DynaBean> columnFields = metaService.select("JE_CORE_VCOLUMNANDFIELD",
                    ConditionsWrapper.builder().apply(" RESOURCECOLUMN_FUNCINFO_ID={0}  ORDER BY SY_ORDERINDEX", funcId));
            for (DynaBean columnField : columnFields) {
                DynaBean dataField = new DynaBean("JE_CORE_EXCELFIELD", false);
                dataField.set(BeanService.KEY_PK_CODE, "JE_CORE_EXCELFIELD_ID");
                dataField.set("SY_ORDERINDEX", columnField.getStr("SY_ORDERINDEX"));
                dataField.set("EXCELFIELD_CODE", columnField.getStr("RESOURCECOLUMN_CODE"));
                dataField.set("EXCELFIELD_NAME", columnField.getStr("RESOURCECOLUMN_NAME"));
                //表单类型   RESOURCEFIELD_XTYPE     RESOURCECOLUMN_XTYPE
                if ("morecolumn".equals(columnField.getStr("RESOURCECOLUMN_XTYPE"))) {
                    dataField.set("EXCELFIELD_XTYPE", "morecolumn");
                } else if ("rownumberer".equals(columnField.getStr("RESOURCECOLUMN_XTYPE"))) {
                    dataField.set("EXCELFIELD_XTYPE", "rownumberer");
                } else if ("uxcheckcolumn".equals(columnField.getStr("RESOURCECOLUMN_XTYPE"))) {
                    dataField.set("EXCELFIELD_XTYPE", "cbbfield");
                    dataField.set("EXCELFIELD_CONFIGINFO", columnField.getStr("RESOURCEFIELD_CONFIGINFO"));
                    if ("0".equalsIgnoreCase(columnField.getStr("RESOURCECOLUMN_HIDDEN"))) {
                        dataField.set("EXCELFIELD_CLDZ", "1");
                        dataField.set("EXCELFIELD_DBZDPZ", columnField.getStr("RESOURECOLUMN_CODE") + "~text");
                    }
                } else if ("datefield".equals(columnField.getStr("RESOURCECOLUMN_XTYPE")) || ("datetimefield".equals(columnField.getStr("RESOURCECOLUMN_XTYPE")))) {
                    dataField.set("EXCELFIELD_XTYPE", columnField.getStr("RESOURCEFIELD_XTYPE"));
                } else {
                    String xtype = columnField.getStr("RESOURCEFIELD_XTYPE");
                    if (ArrayUtils.contains(new String[]{"cbbfield", "rgroup", "cgroup"}, xtype)) {
                        dataField.set("EXCELFIELD_XTYPE", "cbbfield");
                        dataField.set("EXCELFIELD_CONFIGINFO", columnField.getStr("RESOURCEFIELD_CONFIGINFO"));
                        if ("0".equalsIgnoreCase(columnField.getStr("RESOURCECOLUMN_HIDDEN"))) {
                            dataField.set("EXCELFIELD_CLDZ", "1");
                            dataField.set("EXCELFIELD_DBZDPZ", columnField.getStr("RESOURECOLUMN_CODE") + "~text");
                        }
                    } else if (ArrayUtils.contains(new String[]{"treessfield", "treessareafield"}, xtype)) {
                        String[] configs = columnField.getStr("RESOURCEFIELD_CONFIGINFO", "").split(",");
                        if (configs.length > 0) {
                            String ddCode = configs[0];
                            DynaBean dic = metaService.selectOne("JE_CORE_DICTIONARY",
                                    ConditionsWrapper.builder().apply("DICTIONARY_DDTYPE IN ('LIST','TREE') AND DICTIONARY_DDCODE={0}", ddCode));
                            if (dic != null) {
                                dataField.set("EXCELFIELD_XTYPE", "cbbfield");
                                dataField.set("EXCELFIELD_CONFIGINFO", columnField.getStr("RESOURCEFIELD_CONFIGINFO"));
                                if ("0".equalsIgnoreCase(columnField.getStr("RESOURCECOLUMN_HIDDEN"))) {
                                    dataField.set("EXCELFIELD_CLDZ", "1");
                                    dataField.set("EXCELFIELD_DBZDPZ", columnField.getStr("RESOURECOLUMN_CODE") + "~text");
                                }
                            } else {
                                dataField.set("EXCELFIELD_XTYPE", "textfield");
                            }
                        } else {
                            dataField.set("EXCELFIELD_XTYPE", "textfield");
                        }
                    } else {
                        dataField.set("EXCELFIELD_XTYPE", "textfield");
                    }
                }
                dataField.set("EXCELFIELD_WIDTH", columnField.getStr("RESOURCECOLUMN_WIDTH"));
                dataField.set("EXCELFIELD_VALUE", columnField.getStr("RESOURCEFIELD_VALUE"));
                dataField.set("EXCELFIELD_SSDBT", columnField.getStr("RESOURCECOLUMN_MORECOLUMNNAME"));
                dataField.set("EXCELFIELD_XLK", "0");
                dataField.set("EXCELFIELD_EMPTY", "0");
                dataField.set("EXCELFIELD_SJCL", "ALL");
                if ("0".equals(columnField.getStr("RESOURCEFIELD_ALLOWBLANK"))) {
                    dataField.set("EXCELFIELD_EMPTY", "1");
                }
                dataField.set("EXCELFIELD_HIDDEN", columnField.getStr("RESOURCECOLUMN_HIDDEN"));
                dataField.set("JE_CORE_EXCELSHEET_ID", pkValue);
                commonService.buildModelCreateInfo(dataField);
                metaService.insert(dataField);
            }
        } else if (StringUtil.isNotEmpty(tableCode)) {
            DynaBean resourceTable = metaService.selectOne("JE_CORE_RESOURCETABLE",
                    ConditionsWrapper.builder().apply("RESOURCETABLE_TABLECODE={0} AND RESOURCETABLE_TYPE IN ('PT','VIEW','TREE')", tableCode),
                    "JE_CORE_RESOURCETABLE_ID,RESOURCETABLE_TABLECODE");
            if (resourceTable != null) {
                //资源表的列
                List<DynaBean> columns = metaService.select("JE_CORE_TABLECOLUMN",
                        ConditionsWrapper.builder().apply("TABLECOLUMN_RESOURCETABLE_ID={0} ORDER BY SY_ORDERINDEX ", resourceTable.getStr("JE_CORE_RESOURCETABLE_ID")));
                for (int i = 0; i < columns.size(); i++) {
                    DynaBean column = columns.get(i);
                    DynaBean dataField = new DynaBean("JE_CORE_EXCELFIELD", false);
                    dataField.set(BeanService.KEY_PK_CODE, "JE_CORE_EXCELFIELD_ID");
                    dataField.set("SY_ORDERINDEX", i + 1);
                    dataField.set("EXCELFIELD_CODE", column.getStr("TABLECOLUMN_CODE"));
                    dataField.set("EXCELFIELD_NAME", column.getStr("TABLECOLUMN_NAME"));
                    dataField.set("EXCELFIELD_XTYPE", "textfield");
                    dataField.set("EXCELFIELD_WIDTH", "100");
                    dataField.set("EXCELFIELD_VALUE", "");
//						if("NUMBER".equals(columnType) || "FLOAT".equals(columnType)){
                    String columnType = column.getStr("TABLECOLUMN_TYPE");
                    if ("NUMBER".equals(columnType) || "FLOAT".equals(columnType)) {
                        dataField.set("EXCELFIELD_XTYPE", "numberfield");  //字段类型   默认为文本框
                        if ("FLOAT".equals(columnType) && StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_LENGTH")) && column.getInt("TABLECOLUMN_LENGTH") > 0) {
                            dataField.set("EXCELFIELD_CONFIGINFO", column.getInt("TABLECOLUMN_LENGTH"));  //默认小数精度
                        } else if ("NUMBER".equals(columnType)) {
                            dataField.set("EXCELFIELD_CONFIGINFO", "0");  //默认小数精度
                        }
                    } else if ("FLOAT2".equals(columnType)) {
                        dataField.set("EXCELFIELD_XTYPE", "numberfield");  //字段类型   默认为文本框
                        dataField.set("EXCELFIELD_CONFIGINFO", "2");
                    } else if ("DATE".equals(columnType)) {
                        dataField.set("EXCELFIELD_XTYPE", "datefield");  //字段类型   默认为文本框
                    } else if ("DATETIME".equals(columnType)) {
                        dataField.set("EXCELFIELD_XTYPE", "datetimefield");  //字段类型   默认为文本框
                    } else {
                        dataField.set("EXCELFIELD_XTYPE", "textfield");  //字段类型   默认为文本框
                    }
                    dataField.set("EXCELFIELD_SSDBT", "");
                    dataField.set("EXCELFIELD_XLK", "0");
                    dataField.set("EXCELFIELD_EMPTY", "0");
                    dataField.set("EXCELFIELD_SJCL", "ALL");
                    dataField.set("EXCELFIELD_EMPTY", "1");
                    dataField.set("EXCELFIELD_HIDDEN", "0");
                    dataField.set("JE_CORE_EXCELSHEET_ID", pkValue);
                    if ("SY_CREATEORGID".equals(dataField.getStr("EXCELFIELD_CODE"))) {
                        dataField.set("EXCELFIELD_VALUE", "@DEPT_ID@");
                        dataField.set("EXCELFIELD_XTYPE", "textfield");  //字段类型   默认为文本框
                    } else if ("SY_CREATEORG".equals(column.getStr("TABLECOLUMN_CODE"))) {
                        dataField.set("EXCELFIELD_VALUE", "@DEPT_CODE@");
                        dataField.set("EXCELFIELD_XTYPE", "textfield");  //字段类型   默认为文本框
                    } else if ("SY_CREATEORGNAME".equals(column.getStr("TABLECOLUMN_CODE"))) {
                        dataField.set("EXCELFIELD_VALUE", "@DEPT_NAME@");
                        dataField.set("EXCELFIELD_XTYPE", "textfield");  //字段类型   默认为文本框
                    } else if ("SY_CREATETIME".equals(column.getStr("TABLECOLUMN_CODE"))) {
                        dataField.set("EXCELFIELD_VALUE", "@NOW_TIME@");   //默认   年月日 时分秒
                        dataField.set("EXCELFIELD_XTYPE", "datetimefield");   //字段类型  “日期时间”
                        //dataField.set("EXCELFIELD_CONFIGINFO", "Y-m-d");    //配置信息 为  Y-m-d
                    } else if ("SY_CREATEUSERID".equals(dataField.getStr("EXCELFIELD_CODE"))) {
                        dataField.set("EXCELFIELD_VALUE", "@USER_ID@");
                        dataField.set("EXCELFIELD_XTYPE", "textfield");  //字段类型   默认为文本框
                    } else if ("SY_CREATEUSER".equals(column.getStr("TABLECOLUMN_CODE"))) {
                        dataField.set("EXCELFIELD_VALUE", "@USER_CODE@");
                        dataField.set("EXCELFIELD_XTYPE", "textfield");  //字段类型   默认为文本框
                    } else if ("SY_CREATEUSERNAME".equals(column.getStr("TABLECOLUMN_CODE"))) {
                        dataField.set("EXCELFIELD_VALUE", "@USER_NAME@");
                        dataField.set("EXCELFIELD_XTYPE", "textfield");  //字段类型   默认为文本框
                    } else if ("SY_ORDERINDEX".equals(column.getStr("TABLECOLUMN_CODE"))) {
                        dataField.set("EXCELFIELD_VALUE", "0");
                        dataField.set("EXCELFIELD_XTYPE", "numberfield");  //字段类型   默认为文本框
                    } else if ("SY_AUDFLAG".equals(dataField.getStr("EXCELFIELD_CODE"))) {
                        dataField.set("EXCELFIELD_VALUE", "NOSTATUS");
                        dataField.set("EXCELFIELD_XTYPE", "cbbfield");  //字段类型   默认为文本框
                        dataField.set("EXCELFIELD_CONFIGINFO", "JE_AUDFLAG,SY_AUDFLAG,code,S");  //字段类型   默认为文本框
                    } else if ("SY_ACKFLAG".equals(dataField.getStr("EXCELFIELD_CODE"))) {
                        dataField.set("EXCELFIELD_VALUE", "0");
                        dataField.set("EXCELFIELD_XTYPE", "rgroup");  //字段类型   默认为文本框
                        dataField.set("EXCELFIELD_CONFIGINFO", "SY_ACKFLAG,SY_ACKFLAG,code,S");  //字段类型   默认为文本框
                    } else if ("SY_JTGSMC".equals(dataField.getStr("EXCELFIELD_CODE"))) {
                        dataField.set("EXCELFIELD_VALUE", "@USER.dept.jtgsMc@");
                        dataField.set("EXCELFIELD_XTYPE", "textfield");  //字段类型   默认为文本框
                    } else if ("SY_JTGSID".equals(dataField.getStr("EXCELFIELD_CODE"))) {
                        dataField.set("EXCELFIELD_VALUE", "@USER.dept.jtgsId@");
                        dataField.set("EXCELFIELD_XTYPE", "textfield");  //字段类型   默认为文本框
                    }
                    if (column.getStr("TABLECOLUMN_CODE").startsWith("SY_") || column.getStr("TABLECOLUMN_NAME").lastIndexOf("NAME") > 0 || column.getStr("TABLECOLUMN_NAME").lastIndexOf("CODE") > 0 || column.getStr("TABLECOLUMN_NAME").lastIndexOf("ID") > 0) {  //系统字段  默认隐藏
                        dataField.set("EXCELFIELD_HIDDEN", "1");
                        if (dataField.getStr("EXCELFIELD_CODE").equals("SY_ORDERINDEX")) {
                            dataField.set("EXCELFIELD_VALUE", "0");
                        }
                    } else {
                        dataField.set("EXCELFIELD_HIDDEN", "0");
                    }
                    if (column.getStr("TABLECOLUMN_CODE").startsWith("SY_") || column.getStr("TABLECOLUMN_NAME").lastIndexOf("NAME") > 0 || column.getStr("TABLECOLUMN_NAME").lastIndexOf("CODE") > 0 || column.getStr("TABLECOLUMN_NAME").lastIndexOf("ID") > 0) {  //系统字段  默认隐藏
                        dataField.set("EXCELFIELD_HIDDEN", "1");
                        if (dataField.getStr("EXCELFIELD_CODE").equals("SY_ORDERINDEX")) {
                            dataField.set("EXCELFIELD_VALUE", "0");
                        }
                    } else {
                        dataField.set("EXCELFIELD_HIDDEN", "0");
                    }
                    String config = "";
                    //根据列的添加方式 字典添加，表添加来快速初始化功能配置项
                    if (StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_DICCONFIG"))) {
                        config = column.getStr("TABLECOLUMN_DICCONFIG");
                        String dicOtherConfig = column.getStr("TABLECOLUMN_DICQUERYFIELD");
                        if (StringUtil.isNotEmpty(dicOtherConfig)) {
                            if (dicOtherConfig.indexOf("cascadeField:") != -1) {
                                net.sf.json.JSONObject dicConfig = net.sf.json.JSONObject.fromObject(dicOtherConfig);
                                dataField.set("EXCELFIELD_XTYPE", "cbbfield");
                                dataField.set("EXCELFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_DICCONFIG"));
                            } else {
                                dataField.set("EXCELFIELD_XTYPE", "treessfield");
                                dataField.set("EXCELFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_DICCONFIG"));
                            }
                        } else {
                            dataField.set("EXCELFIELD_XTYPE", "cbbfield");
                            dataField.set("EXCELFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_DICCONFIG"));
                        }
                    } else if (StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_QUERYCONFIG"))) {
                        config = column.getStr("TABLECOLUMN_QUERYCONFIG");
                        if (column.getStr("TABLECOLUMN_QUERYCONFIG").startsWith("JE_CORE_QUERYUSER,")) {
                            dataField.set("EXCELFIELD_XTYPE", "vueuserfield");
                            dataField.set("EXCELFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_QUERYCONFIG"));
                        } else {
                            dataField.set("EXCELFIELD_XTYPE", "gridssfield");
                            dataField.set("EXCELFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_QUERYCONFIG"));
                        }
                    }
                    if ("SY_WARNFLAG".equals(column.getStr("TABLECOLUMN_CODE"))) {
                        dataField.set("EXCELFIELD_XTYPE", "cbbfield");
                        dataField.set("EXCELFIELD_CONFIGINFO", "JE_WARNFLAG");
                    }
                    commonService.buildModelCreateInfo(dataField);
                    metaService.insert(dataField);

                }
            } else {
//                List<Model> models = pcDataService.loadSql("", " SELECT * FROM " + tableCode + " WHERE 1!=1 ", new ArrayList<DbFieldVo>());
                int order = 1;
//                for (Model model : models) {
//                    DynaBean dataField = new DynaBean("JE_CORE_EXCELFIELD", false);
//                    dataField.set(BeanService.KEY_PK_CODE, "JE_CORE_EXCELFIELD_ID");
//                    dataField.set("SY_ORDERINDEX", order);
//                    dataField.set("EXCELFIELD_CODE", model.getName());
//                    dataField.set("EXCELFIELD_NAME", "");
//                    dataField.set("EXCELFIELD_XTYPE", "textfield");
//                    dataField.set("EXCELFIELD_WIDTH", "100");
//                    dataField.set("EXCELFIELD_VALUE", "");
//                    dataField.set("EXCELFIELD_SSDBT", "");
//                    dataField.set("EXCELFIELD_XLK", "0");
//                    dataField.set("EXCELFIELD_EMPTY", "0");
//                    dataField.set("EXCELFIELD_SJCL", "ALL");
//                    dataField.set("EXCELFIELD_EMPTY", "1");
//                    dataField.set("EXCELFIELD_HIDDEN", "0");
//                    dataField.set("JE_CORE_EXCELSHEET_ID", pkValue);
//                    commonService.buildModelCreateInfo(dataField);
//                    metaService.insert(dataField);
//                    order++;
//                }
            }
        }
    }

    @Override
    public List<Map<String, Object>> funcTemplateListById(String sheetId) {
        //查询功能对应的模板
        List<Map<String, Object>> newList = new ArrayList<>();
        //人大金仓!=''查询不出数据
        String sql = "select t.SY_ORDERINDEX,t.STARTROWS,t.JE_CORE_EXCELSHEET_ID,t.JE_CORE_EXCELGROUP_ID,n.GROUPNAME,n.EXCELGROUP_FILE from JE_CORE_EXCELSHEET t INNER JOIN JE_CORE_EXCELGROUP n on n.JE_CORE_EXCELGROUP_ID = t.JE_CORE_EXCELGROUP_ID where JE_CORE_EXCELSHEET_ID = {0}";
        List<Map<String, Object>> list = metaService.selectSql(sql, sheetId);
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }
        for (Map<String, Object> map : list) {
            if (!Objects.isNull(map.get("EXCELGROUP_FILE"))) {
                if (!Strings.isNullOrEmpty(String.valueOf(map.get("EXCELGROUP_FILE")))) {
                    newList.add(map);
                }
            }
        }
        return newList;
    }


    @Override
    public List<List<Object>> buildExportData(String funcId, List<DynaBean> datas, Map<String, Map<String, String>> ddInfos, List<DynaBean> formColumns) {
        List<DynaBean> funcGridFileds = metaService.select("JE_CORE_RESOURCECOLUMN", ConditionsWrapper.builder()
                .eq("RESOURCECOLUMN_FUNCINFO_ID", funcId).in("RESOURCECOLUMN_XTYPE", "rownumberer", "uxcolumn")
                .eq("RESOURCECOLUMN_HIDDEN", "0").orderByAsc("SY_ORDERINDEX"), COLUMNS);
        List<List<Object>> list = new ArrayList<>();
        int i = 1;
        for (DynaBean dynaBean : datas) {
            List<Object> dataMap = new ArrayList<>();
            HashMap<String, Object> map = dynaBean.getValues();
            for (DynaBean gridFiled : funcGridFileds) {
                String filedCode = gridFiled.getStr("RESOURCECOLUMN_CODE");
                String type = gridFiled.getStr("RESOURCECOLUMN_XTYPE");
                if (type.equals("rownumberer")) {
                    dataMap.add(i);
                    i++;
                    continue;
                }
                DynaBean formColumn = null;
                for (DynaBean fc : formColumns) {
                    if (fc.getStr("RESOURCECOLUMN_CODE").equals(filedCode)) {
                        formColumn = fc;
                    }
                }
                if (formColumn == null) {
                    throw new PlatformException(String.format("获取%s导出字段配置信息出错！", filedCode), PlatformExceptionEnum.UNKOWN_ERROR);
                }
                Object value = buildValue(map.get(filedCode), formColumn, ddInfos);
                dataMap.add(value);
            }
            list.add(dataMap);
        }
        return list;
    }

    private Object buildValue(Object value, DynaBean formColumn, Map<String, Map<String, String>> ddInfos) {
        if (Objects.isNull(value)) {
            return "";
        }
        String stringValue = String.valueOf(value);
        if (Strings.isNullOrEmpty(stringValue)) {
            return "";
        }
        String type = formColumn.getStr("RESOURCEFIELD_XTYPE");
        return ExcelExportConverterFactory.getConverter(type).converter(stringValue, formColumn, ddInfos);
    }

    @Override
    public InputStream exportExcel(JSONObject params, HttpServletRequest request) {
        String styleType = params.getString("styleType");
        ExcelRpcExportService excelRpcExportService = ExcelExportFactory.getValidator(styleType);
        return excelRpcExportService.export(params, request);
    }
}
